package com.chuantou.yuba.ui.widget;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.adapter.ExpressionAdapter;
import com.chuantou.yuba.adapter.ExpressionPagerAdapter;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.CommentResponseTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.widget.KeyboardLayout.onKybdsChangeListener;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;
import com.easemob.applib.utils.SmileUtils;

public class CommentDialog extends DialogFragment implements OnClickListener {

	private Context mContext;
	private EditText mCommentInputView;
	private TextView mSendBtn;
	private ImageView mAddEmojiView;
	private ImageView mShowKeyboardView;
	private LinearLayout mEmojiContainer;
	private LinearLayout mInputLayout;
	private Listener<CommentResponseTO> mListener;
	private long mTrendsId;
	private long mReplyUid;
	private String mReplyNickname;
	private UserTO mUser;
	private HashMap<String, String> mData;
	private ViewPager mExpressionViewpager;
	private List<String> reslist;

	public CommentDialog(Context context, UserTO user, long trendsId, long replyUid, String replyNickname, HashMap<String, String> data) {
		super();
		setStyle(R.style.CommentDialog, R.style.CommentDialog);
		this.mContext = context;
		this.mTrendsId = trendsId;
		this.mReplyUid = replyUid;
		this.mReplyNickname = replyNickname;
		this.mUser = user;
		this.mData = data;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Window window = getDialog().getWindow();
		// WindowManager.LayoutParams attributes = window.getAttributes();
		// attributes.gravity = Gravity.BOTTOM;
		window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
		// window.setBackgroundDrawable(new
		// ColorDrawable(getResources().getColor(R.color.translucence)));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.trends_comment, null);
		setupViews(view);
		return view;
	}

	private void setupViews(View view) {
		// this.setFocusable(true);
		final KeyboardLayout rootView = (KeyboardLayout) view.findViewById(R.id.root);
		mCommentInputView = (EditText) view.findViewById(R.id.comment);
		mCommentInputView.setOnClickListener(this);
		rootView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				dismiss();
				return true;
			}
		});
		rootView.setOnkbdStateListener(new onKybdsChangeListener() {

			public void onKeyBoardStateChange(int state) {
				switch (state) {
				case KeyboardLayout.KEYBOARD_STATE_HIDE:
					if (mEmojiContainer.getVisibility() == View.GONE) {
						dismiss();
					}
					break;
				}
			}
		});
		if (!TextUtils.isEmpty(mReplyNickname) && mReplyUid > 0) {
			mCommentInputView.setHint(mContext.getString(R.string.comment_reply_sb, mReplyNickname));
		}
		mSendBtn = (TextView) view.findViewById(R.id.send);
		mSendBtn.setOnClickListener(this);
		mAddEmojiView = (ImageView) view.findViewById(R.id.add_emoji);
		mAddEmojiView.setOnClickListener(this);
		mShowKeyboardView = (ImageView) view.findViewById(R.id.show_keyboard);
		mShowKeyboardView.setOnClickListener(this);
		mEmojiContainer = (LinearLayout) view.findViewById(R.id.ll_face_container);
		mExpressionViewpager = (ViewPager) view.findViewById(R.id.vPager);
		mInputLayout = (LinearLayout) view.findViewById(R.id.input_layout);
		// 表情list
		reslist = getExpressionRes(35);
		// 初始化表情viewpager
		List<View> views = new ArrayList<View>();
		View gv1 = getGridChildView(1);
		View gv2 = getGridChildView(2);
		views.add(gv1);
		views.add(gv2);
		mExpressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
		UiUtil.showInputKeyboard(mContext, mCommentInputView);
	}

	public List<String> getExpressionRes(int getSum) {
		List<String> reslist = new ArrayList<String>();
		for (int x = 1; x <= getSum; x++) {
			String filename = "ee_" + x;
			reslist.add(filename);
		}
		return reslist;

	}

	/**
	 * 获取表情的gridview的子view
	 * 
	 * @param i
	 * @return
	 */
	private View getGridChildView(int i) {
		View view = View.inflate(mContext, R.layout.expression_gridview, null);
		ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
		List<String> list = new ArrayList<String>();
		if (i == 1) {
			List<String> list1 = reslist.subList(0, 20);
			list.addAll(list1);
		} else if (i == 2) {
			list.addAll(reslist.subList(20, reslist.size()));
		}
		list.add("delete_expression");
		final ExpressionAdapter expressionAdapter = new ExpressionAdapter(mContext, 1, list);
		gv.setAdapter(expressionAdapter);
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String filename = expressionAdapter.getItem(position);
				try {
					// 文字输入框可见时，才可输入表情
					// 按住说话可见，不让输入表情
					if (filename != "delete_expression") { // 不是删除键，显示表情
						// 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
						Class clz = Class.forName(SmileUtils.class.getName());
						Field field = clz.getField(filename);
						mCommentInputView.append(SmileUtils.getSmiledText(mContext, (String) field.get(null)));
					} else { // 删除文字或者表情
						mCommentInputView.onKeyDown(KeyEvent.KEYCODE_DEL, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
					}
				} catch (Exception e) {
				}

			}
		});
		return view;
	}

	public void setListener(Listener<CommentResponseTO> listener) {
		this.mListener = listener;
	}

	@Override
	public void onClick(View v) {
		if (UiUtil.isFastDoubleClick())
			return;
		switch (v.getId()) {
		case R.id.send:
			String comment = mCommentInputView.getText().toString().trim();
			if (TextUtils.isEmpty(comment)) {
				Toast.makeText(mContext, R.string.comment_input_length_error, Toast.LENGTH_SHORT).show();
				return;
			}
			sendComment(comment);
			break;
		case R.id.add_emoji:
			mShowKeyboardView.setVisibility(View.VISIBLE);
			mAddEmojiView.setVisibility(View.GONE);
			mEmojiContainer.setVisibility(View.VISIBLE);
			UiUtil.hideInputKeyboard(mContext, mCommentInputView);
			break;
		case R.id.show_keyboard:
			mShowKeyboardView.setVisibility(View.GONE);
			mAddEmojiView.setVisibility(View.VISIBLE);
			mEmojiContainer.setVisibility(View.GONE);
			UiUtil.showInputKeyboard(mContext, mCommentInputView);
			break;
		case R.id.comment:
			mAddEmojiView.setVisibility(View.VISIBLE);
			mShowKeyboardView.setVisibility(View.GONE);
			mEmojiContainer.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}

	private void sendComment(final String comment) {
		String url = UriHelper.getReplyTrendsUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_UID, String.valueOf(mUser.getUid()));
		params.put(UriHelper.PARAMS_TOKEN, mUser.getToken());
		params.put(UriHelper.PARAMS_ID, String.valueOf(mTrendsId));
		params.put(UriHelper.PARAMS_CONTENT, comment);
		if (mReplyUid > 0) {
			params.put(UriHelper.PARAMS_REPLY_UID, String.valueOf(mReplyUid));
		}
		GsonRequest<CommentResponseTO> request = new GsonRequest<CommentResponseTO>(Method.POST, url, new Listener<CommentResponseTO>() {

			@Override
			public void onResponse(CommentResponseTO response) {
				if (getActivity() != null && response != null && response.isSuccess()) {
					mData.put(Constants.EXTRA_DATA, comment);
					mCommentInputView.setText("");
				}
				if (mListener != null) {
					mListener.onResponse(response);
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
			}
		}, params, CommentResponseTO.class);
		RequestManager.startRequest(mContext, request);
	}
}
